package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialSettingEntity;
import city.spring.modules.material.service.MaterialSettingService;
import city.spring.modules.material.service.ShelflevelService;
import city.spring.modules.material.service.StorehouseService;
import city.spring.modules.material.service.SupplierService;
import city.spring.modules.material.vo.MaterialVO;
import city.spring.service.UnitmeasurementService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/materialSetting")
public class MaterialSettingController extends ApiController {
    protected final UnitmeasurementService unitmeasurementService;
    /**
     * <strong>物资管理</strong> Service
     */
    private final MaterialSettingService materialService;
    private final SupplierService supplierService;
    private final StorehouseService storehouseService;
    private final ShelflevelService shelflevelService;
    /**
     * 实体类（物资管理）可排序字段
     */
    private final List<SFunction<MaterialSettingEntity, ?>> entityOrderFields;


    public MaterialSettingController(MaterialSettingService materialService, SupplierService supplierService, UnitmeasurementService unitmeasurementService, StorehouseService storehouseService, ShelflevelService shelflevelService) {
        this.materialService = materialService;
        this.supplierService = supplierService;
        this.storehouseService = storehouseService;
        this.unitmeasurementService = unitmeasurementService;
        this.shelflevelService = shelflevelService;
        this.entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialSettingEntity::getId);
        entityOrderFields.add(MaterialSettingEntity::getName);
        entityOrderFields.add(MaterialSettingEntity::getCategoryId);
        entityOrderFields.add(MaterialSettingEntity::getDescription);
        entityOrderFields.add(MaterialSettingEntity::getStatus);
    }

    /**
     * 获取全部的 <strong>物资管理</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MaterialSettingEntity entity) {
        LambdaQueryChainWrapper<MaterialSettingEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>物资管理</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "category_id", direction = Sort.Direction.ASC), @SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialVO entity) {

        QueryWrapper<? extends MaterialSettingEntity> queryWrapper = buildQuery(entity);
        return success(materialService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

    }

    /**
     * 分页获取 <strong>物资管理</strong> 列表
     * 获取物资选择页面
     *
     * @param pageable 分页参数信息
     */
    @GetMapping("/getMaterialPage")
    public Object getMaterialPage(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "category_id", direction = Sort.Direction.ASC), @SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialVO entity) {

        QueryWrapper<? extends MaterialSettingEntity> queryWrapper = getMaterialPage(entity);
        return success(materialService.getMaterialPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }


    /**
     * 获取一个 <strong>物资管理</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

//        return success(materialService.getById(id));

        QueryWrapper<MaterialVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialVO> records = materialService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    @GetMapping("/getMaterial/{id}")
    public Object getMaterialIswarehousinginfo(@PathVariable String id) {

//        return success(materialService.getById(id));

        QueryWrapper<MaterialVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialVO> records = materialService.getMaterialPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>物资管理</strong>
     *
     * @param entity 新增的信息
     */
    @PostMapping
    public Object add(@RequestBody MaterialSettingEntity entity) {
        materialService.save(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>物资管理</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MaterialSettingEntity entity) {
        entity.setId(id);
        materialService.updateMaterial(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>物资管理</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialService.removeById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>物资管理</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>物资管理</strong>
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialSettingEntity> buildLambdaQuery(MaterialSettingEntity entity) {
        LambdaQueryChainWrapper<MaterialSettingEntity> lambdaQuery = materialService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MaterialSettingEntity::getId, entity.getId());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getName()), MaterialSettingEntity::getName, entity.getName());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getCategoryId()), MaterialSettingEntity::getCategoryId, entity.getCategoryId());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialSettingEntity> buildQuery(MaterialVO entity) {
        QueryWrapper<MaterialSettingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.eq(StringUtils.isNotBlank(entity.getCategoryId()), "t1.category_id", entity.getCategoryId());
        wrapper.eq(StringUtils.isNotBlank(entity.getCname()), "t3.cname", entity.getCname());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getStatus()), "t1.status", entity.getStatus());
        wrapper.like(entity.getUnitprice() != null, "t1.unitprice", entity.getUnitprice());
        wrapper.like(StringUtils.isNotBlank(entity.getDescription()), "t1.description", entity.getDescription());
        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialSettingEntity> getMaterialPage(MaterialVO entity) {
        QueryWrapper<MaterialSettingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getCategoryId()), "t1.category_id", entity.getCategoryId());
        wrapper.eq(StringUtils.isNotBlank(entity.getCname()), "t3.cname", entity.getCname());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.like(StringUtils.isNotBlank(entity.getStatus()), "t1.status", entity.getStatus());
        wrapper.like(entity.getUnitprice() != null, "t1.unitprice", entity.getUnitprice());
        wrapper.like(StringUtils.isNotBlank(entity.getDescription()), "t1.description", entity.getDescription());
        return wrapper;
    }

    /**
     * 根据物资类别查找该类别下的物资 （物资信息树形结构使用）
     *
     * @param pageable
     * @param categoryId
     * @return
     */
    @GetMapping("/getMaterialByCategoryId")
    public Object getMaterialByCategoryIdlist(@PageableDefault Pageable pageable, MaterialVO entity, String categoryId) {

        QueryWrapper<? extends MaterialSettingEntity> queryWrapper = buildQueryByCategoryId(entity);
        return success(materialService.MaterialByCategoryIdlistPage(MyBatisUtils.toPage(pageable), queryWrapper, categoryId));

    }

    private QueryWrapper<MaterialSettingEntity> buildQueryByCategoryId(MaterialVO entity) {
        QueryWrapper<MaterialSettingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCategoryId()), "t1.category_id", entity.getCategoryId());
        wrapper.like(StringUtils.isNotBlank(entity.getStatus()), "t1.status", entity.getStatus());
        wrapper.like(entity.getUnitprice() != null, "t1.unitprice", entity.getUnitprice());
        wrapper.like(StringUtils.isNotBlank(entity.getDescription()), "t1.description", entity.getDescription());
        return wrapper;
    }

}
